package com.ipet.app.api;


import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.util.DialogUtils;
import com.ipet.app.R;
import com.ipet.app.bean.apiResponseBean.BaseResponse;
import com.ipet.app.common.App;
import com.ipet.app.ui.activity.LoginActivity;
import com.ipet.app.ui.empty.EmptyLayout;
import com.ipet.app.util.ColoredSnackbar;
import com.jude.easyrecyclerview.swipe.SwipeRefreshLayout;

import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by jindongping on 16/3/17.
 * Response,处理网络错误情况.
 */
public abstract class BaseCallBack<T extends BaseResponse> implements Callback<T> {

    private View view;
    private SwipeRefreshLayout refreshLayout;
    private MaterialDialog dialog;
    private EmptyLayout emptyLayout;

    /**
     * 使用该构造函数 网络错误时会用snack提示
     */
    public BaseCallBack(View view) {
        this.view = view;
    }

    /**
     * 使用该构造函数 界面啥都木有
     */
    public BaseCallBack() {

    }

    /**
     * 使用该构造函数网络错误时会用snack提示,无论成功或者失败后 dialog都消失
     * @param view snackBar依附的view
     */
    public BaseCallBack(View view, MaterialDialog dialog) {
        this(view,null,dialog,null);

    }

    /**
     * 使用该构造函数网络错误时会用snack提示,无论成功或者失败后 refreshLayout都消失
     * @param view snackBar依附的view
     * @param refreshLayout 下拉刷新view
     */
    public BaseCallBack(View view, SwipeRefreshLayout refreshLayout) {
       this(view,refreshLayout,null,null);
    }

    /**
     * * 使用该构造函数网络错误时会用snack提示,无论成功或者失败后 refreshLayout都消失,emptyLayout会对网络情况作出显示
     * @param view snackBar依附的view
     * @param refreshLayout 下拉刷新view
     * @param emptyLayout emptyView
     */
    public BaseCallBack(View view, SwipeRefreshLayout refreshLayout,EmptyLayout emptyLayout) {
        this(view,refreshLayout,null,emptyLayout);
    }

    public BaseCallBack(View view, SwipeRefreshLayout refreshLayout, MaterialDialog dialog, EmptyLayout emptyLayout) {
        this.view = view;
        this.refreshLayout = refreshLayout;
        this.dialog = dialog;
        this.emptyLayout = emptyLayout;
    }

    //网络成功请求
    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (dialog != null)
            dialog.cancel();
        if (refreshLayout != null)
            refreshLayout.setRefreshing(false);
        if(emptyLayout!=null)
            emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        if (response.body().isSucess()) {
            onRequestSuccess(response.body());
        } else {
            onRequestFail(response.body().getMsg());
        }
    }

    //处理网络错误
    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (dialog != null)
            dialog.cancel();
        if (refreshLayout != null)
            refreshLayout.setRefreshing(false);
        if(emptyLayout!=null)
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        if (view != null) {
            t.printStackTrace();
            if (t.toString().contains("java.net.ConnectException")) {
                snackErr(view, "网络连接异常，请检查网络。");
            } else if (t.toString().contains("java.net.SocketTimeoutException")) {
                snackErr(view, "连接超时");
            } else {
                snackErr(view, "未知错误");
            }
        }
    }
    //api响应正确
    public abstract void onRequestSuccess(T response);

    //api响应错误 如果是phpSession失效 则跳转到登陆界面
    public void onRequestFail(String errMsg) {
        if (view != null)
            snackShow(view, errMsg);
        if(errMsg.contains("请先登录")){
            Intent intent= new Intent( App.getContext(),LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            App.getContext().startActivity(intent);
        }
        //在其它地方登陆
        if(errMsg.contains("已在")){
            TimerTask task = new TimerTask(){
                public void run(){
                    Intent intent= new Intent( App.getContext(),LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    App.getContext().startActivity(intent);
                }
            };
            Timer timer = new Timer();
            timer.schedule(task, 2000);
        }
    }


    protected void snackShow(View view, @NonNull CharSequence msg) {
        Snackbar.make(view, msg, Snackbar.LENGTH_SHORT).setAction("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        }).setActionTextColor(DialogUtils.getColor(view.getContext(), R.color.colorPrimary)).show();
    }


    protected void snackErr(View view, @NonNull CharSequence msg) {
        ColoredSnackbar.alert(Snackbar.make(view, msg, Snackbar.LENGTH_SHORT).setAction("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        })).setActionTextColor(DialogUtils.getColor(view.getContext(), R.color.colorPrimary)).show();
    }


}
